import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { ARTICLE_BROWSER, RedisService } from "../common/service/redis.service";
import { ArticlesService } from "../articles/articles.service";

@Injectable()
export class TaskService {
  constructor(
    private readonly logger: Logger,
    private readonly redisService: RedisService,
    private readonly articlesService: ArticlesService
  ) {
    this.logger = new Logger('TaskService');
  }
  /**
   * 每天凌晨4点同步Redis浏览量到数据库
   */
  @Cron(CronExpression.EVERY_DAY_AT_4AM)
  async syncRedisToDatabase() {
    this.logger.log('开始同步Redis浏览量到数据库');
    try {
      const redisData = await this.redisService.getAllWithPrefix(ARTICLE_BROWSER);
      for (const [key, value] of Object.entries(redisData)) {
        const articleId = key.replace(ARTICLE_BROWSER, '');
        await this.articlesService.update(parseInt(articleId), {browse:parseInt(value)});
      }
      this.logger.log('同步Redis浏览量到数据库完成');
    } catch (error) {
      this.logger.error('同步Redis浏览量到数据库时发生错误:', error);
    }
  }
}

